import express from 'express';
import http from 'node:http';
import compression from 'compression'
import bodyParser from 'body-parser'
import { Server, Socket } from 'socket.io'

const app = express();
const httpServer = http.createServer(app);
const io = new Server(httpServer);

app.use(compression());
app.use(bodyParser.json());

const userList: Map<Socket, string> = new Map();
io.on('connection', (socket: Socket) => {
    socket.on('login', (userName: string) => {
        console.log(`User ${userName} connected`);
        userList.set(socket, userName);
    })
    socket.on('message', (message: string) => {
        console.log(`Message from ${userList.get(socket)}: 
        ${message}`);
        const userName = userList.get(socket); // 这个是用户名
        socket.broadcast.emit('message',
            { userName, message });
    })
    socket.on('disconnect', () => {
        userList.delete(socket);
    });
})

app.use((_, res) => {
    res.status(404).send('Not Found');
});

httpServer.listen(3000, () => {
    console.log('Server is running on port 3000');
});